//
//  RegUtil.swift
//  正则表达式相关方法
//
//  Created by smile on 2019/6/30.
//  Copyright © 2019 ixuea. All rights reserved.
//

import Foundation

class RegUtil {
    /// 匹配mention的正则表达式
    /// ？表示禁用贪婪模式，详细的请参考《详解正则表达式》课程
    static let REG_MENTION = "@([\\u4e00-\\u9fa5a-zA-Z0-9_-]{2,30})"
    
    /// 匹配hashTag的正则表达式
    static let REG_HASH_TAG = "#(.*?)#"
    
    /// 查找Mentions
    ///
    /// - Parameter data: <#data description#>
    /// - Returns: <#return value description#>
    static func findMentions(_ data:String) -> [NSTextCheckingResult] {
        return find(REG_MENTION, data)
    }
    
    /// 查找话题
    ///
    /// - Parameter data: <#data description#>
    /// - Returns: <#return value description#>
    static func findHashTag(_ data:String) -> [NSTextCheckingResult] {
        return find(REG_HASH_TAG, data)
    }
    
    /// 正则表达式查找
    ///
    /// - Parameters:
    ///   - reg: 正则表达式
    ///   - data: 被查找的数据
    /// - Returns:
    static func find(_ reg:String,_ data:String) -> [NSTextCheckingResult] {
        //创建一个匹配对象
        let regular = try! NSRegularExpression(pattern: reg, options: .caseInsensitive)
        
        //开始匹配
        return regular.matches(in: data, options: [], range: NSRange(location: 0, length: data.count))
    }
}
